﻿using Himp.TaskScheduling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace Himp.TaskScheduling
{
    /// <summary>
    /// 事件消息接收
    /// </summary>
    public class EventMsgRecService : TaskSchedulingAppService, IEventMsgRecService
    {
        private readonly IRepository<EventMsgRec, Guid> _msgSendRecRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="msgSendRecRepository"></param>
        /// <param name="hubContext"></param>
        public EventMsgRecService(IRepository<EventMsgRec, Guid> msgSendRecRepository)
        {
            _msgSendRecRepository = msgSendRecRepository;
        }

        /// <summary>
        /// 获取消息发送记录
        /// </summary>
        /// <returns></returns>
        public async Task<PagedResultDto<EventMsgRecDto>> GetListAsync(EventMsgRecInput input)
        {
            if (input.TopicFullPath == null)
            {
                input.TopicFullPath = [];
            }

            var iQuery = await _msgSendRecRepository.GetQueryableAsync();
            iQuery = iQuery.Where( i => input.TopicFullPath.Contains(i.TopicFullPath));
            iQuery = iQuery.OrderByDescending(i => i.CreationTime);

            if (input.Pi == 0)
            {
                var itemsDto = ObjectMapper.Map<List<EventMsgRec>, List<EventMsgRecDto>>(iQuery.ToList());

                return new PagedResultDto<EventMsgRecDto>(itemsDto.Count, itemsDto);
            }
            else
            {
                var totalCount = iQuery.Count();
                var items = iQuery.Page(input.Pi, input.Ps);
                var itemsDto = ObjectMapper.Map<List<EventMsgRec>, List<EventMsgRecDto>>(items.ToList());

                return new PagedResultDto<EventMsgRecDto>(totalCount, itemsDto);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<EventMsgRecDto> PostAsync(EventMsgRecCreateDto input)
        {
            var eventMsgRecvRec = ObjectMapper.Map<EventMsgRecCreateDto, EventMsgRec>(input);
            eventMsgRecvRec = await _msgSendRecRepository.InsertAsync(eventMsgRecvRec);
            var itemDto = ObjectMapper.Map<EventMsgRec, EventMsgRecDto>(eventMsgRecvRec);

            return itemDto;
        }
    }
}
